package com.sxdz.web.order

import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.sxdz.api.webService.CalculatorDelegate
import com.sxdz.api.webService.ResultVo
import com.sxdz.constant.CommonConstant
import com.sxdz.constant.GlobalConstant
import com.sxdz.constant.MessageConstant
import com.sxdz.controller.cache.SessionCache
import com.sxdz.controller.handler.CalculatorHandler
import com.sxdz.controller.service.goods.IGoodsService
import com.sxdz.controller.service.order.IOrderDetailService
import com.sxdz.controller.service.order.IOrderService
import com.sxdz.controller.service.wechat.IWechatSubService
import com.sxdz.models.TGoodsInfo
import com.sxdz.models.TOrder
import com.sxdz.models.TOrderDetail
import com.sxdz.models.TblWechatSubscribe
import com.sxdz.models.api.PayResult
import com.sxdz.models.common.JsonResult
import com.sxdz.pay.PayMentApi
import com.toolbox.utils.DateUtil
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController

import javax.servlet.http.HttpServletRequest

/**
 * Created by lzw on 2016/8/15.
 */
@RestController
@CompileStatic
@TypeChecked
@RequestMapping("orderPay")
class   PayOrderAction {
    //导入
    Logger logger = LoggerFactory.getLogger(this.getClass())
    @Autowired
    private IOrderService orderService

    @Autowired
    private IOrderDetailService orderDetailService

    @Autowired
    private IWechatSubService wechatSubService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private SessionCache sessionCache;

    /**
     * 商城订单支付
     */
    @RequestMapping(value = "pay", method = RequestMethod.POST)
    @ResponseBody
    pay(HttpServletRequest request, TOrder tOrder, String orderDetJson, String openid) {
        try {
            //插入订单
            TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
            if (wechatSubscribe == null) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
            }
            String res = "";
            String outtradeno = sessionCache.getCache(openid + "outtradeno").toString();

            tOrder.setOutTradeNo(outtradeno)//商户订单号
            tOrder.setUserId(wechatSubscribe.getSubcribeId() as Long)//获取userId
            tOrder.setGoodsModule("1")//1:实体商品 2:套餐 3:收视费 4虚拟产品  这里默认是1
            tOrder.setAccountDate(DateUtil.getTimeToString());//账单日期
            tOrder.setCreateTime(new Date().getTime())
            tOrder.setPayFee(tOrder.getTotalFee())//目前支付金额等于总金额
            tOrder.payStatus = CommonConstant.PayStatus.NotPay.value//默认未支付
            tOrder.setIsActive(CommonConstant.IsActive.True.value)//默认有效
            Long orderSum = orderService.addBasic(tOrder);
            if (orderSum > 0) {//插入详情
                TOrderDetail orderDetail;
                JSONArray jsonArray = JSONArray.fromObject(orderDetJson)
                Long orderDetSum = 0L;
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    orderDetail = new TOrderDetail();
                    orderDetail.setOrderId(tOrder.getId());
                    orderDetail.setItemName(jsonObject.get("itemName").toString())
                    orderDetail.setItemDesc(jsonObject.get("itemDesc").toString())
                    orderDetail.setItemSum(Long.parseLong(jsonObject.get("itemSum").toString()))
                    orderDetail.setItemNum(Long.parseLong(jsonObject.get("itemNum").toString()))
                    orderDetSum = orderDetailService.addBasic(orderDetail);
                }
                if (orderDetSum > 0) {
                    //初始化支付接口
                    if (!"7551000001".equals(GlobalConstant.getString("mch_id"))) { //非测试商户ID
                        res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), tOrder.getTotalFee().toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    } else {
                        res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), 1.toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    }
                }
                ObjectMapper ompay = new ObjectMapper();
                ompay.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                PayResult custInfo = ompay.readValue(res, PayResult.class);
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.SUCCESS, custInfo.token_id)
            } else {
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "生成订单失败", null)
            }


        } catch (Exception e) {
            logger.error("订单支付失败!")
            sessionCache.delCache(openid + "outtradeno");
            return new JsonResult<Object>(MessageConstant.FAILURE, null)
        } /*finally {

        }*/
    }

    /**
     * 商城订单支付2
     */
    @RequestMapping(value = "pay2", method = RequestMethod.POST)
    @ResponseBody
    pay2(HttpServletRequest request, TOrder tOrder, String orderDetJson, String openid) {
        try {
            //插入订单
            TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
            if (wechatSubscribe == null) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
            }
            String res = "";
            //获取商品信息
            JSONArray jsonArray = JSONArray.fromObject(orderDetJson)
                List<String> orderidList=jsonArray.toList();
            List<TGoodsInfo> goodsInfoList=new ArrayList<TGoodsInfo>();
            Integer amounSum=0;
            String qModule="1";
            String qModel="";
            String orderStatus;
            Integer goodsFreight=0;
            for(String str:orderidList){
                String id=str;
                if(str==null || str==""){
                    continue;
                }
                TGoodsInfo goodsInfo=goodsService.findObjByKey(Long.valueOf(str)) as TGoodsInfo;
                if(goodsInfo==null){
                    return new JsonResult<Object>(MessageConstant.FAIL_QUERY.code, "未获取到商品信息", null)
                }else{
                    amounSum+=goodsInfo.goodsPrice;
                    if("1".equals(goodsInfo.goodsModule) || "4".equals(goodsInfo.goodsModule)){
                        qModule=goodsInfo.goodsModule;
                        qModel=goodsInfo.goodsModel;
                        amounSum+=goodsInfo.getGoodsFreight();
                        goodsFreight=goodsInfo.getGoodsFreight();
                        if("1".equals(goodsInfo.goodsModule)){//订单状态默认2   备货中
                            orderStatus=CommonConstant.OrderStatus.BHZ.value;
                        }
                    }
                    goodsInfoList.add(goodsInfo);
                }
            }


            String outtradeno = sessionCache.getCache(openid + "outtradeno").toString();
            tOrder.setOutTradeNo(outtradeno)//商户订单号
            tOrder.setUserId(wechatSubscribe.getSubcribeId() as Long)//获取userId
            tOrder.setGoodsModule(qModule)//1:实体商品 2:套餐 3:收视费 4虚拟产品  这里默认是1
            tOrder.setAccountDate(DateUtil.getTimeToString());//账单日期
            tOrder.setCreateTime(new Date().getTime())
            tOrder.setPayFee(amounSum  as Long)//目前支付金额等于总金额
            tOrder.setTotalFee(amounSum as Long)
            tOrder.setGoodsNum(1);
            tOrder.setReserve1(qModel);//型号
            tOrder.payStatus = CommonConstant.PayStatus.NotPay.value//默认未支付
            //tOrder.orderStatus=orderStatus;
            tOrder.setReserve2(openid);
            tOrder.setIsActive(CommonConstant.IsActive.True.value)//默认有效
            Long orderSum = orderService.addBasic(tOrder);
            if (orderSum > 0) {//插入详情
                TOrderDetail orderDetail;
                Long orderDetSum = 0L;
                for (int i = 0; i < goodsInfoList.size(); i++) {
                    TGoodsInfo tGoodsInfo = (TGoodsInfo) goodsInfoList.get(i);
                    orderDetail = new TOrderDetail();
                    orderDetail.setOrderId(tOrder.getId());
                    if("2".equals(tGoodsInfo.getGoodsModule())){
                        orderDetail.setItemName(tGoodsInfo.getDetails())
                    }else{
                        orderDetail.setItemName(tGoodsInfo.getGoodsName())
                    }
                    orderDetail.setItemDesc(tGoodsInfo.getGoodsDescribe())
                    orderDetail.setItemSum(tGoodsInfo.getGoodsPrice() as Long)
                    orderDetail.setItemNum(1L)
                    orderDetSum = orderDetailService.addBasic(orderDetail);
                }
                //添加运费
                if("1".equals(qModule)){
                    orderDetail = new TOrderDetail();
                    orderDetail.setOrderId(tOrder.getId());
                    orderDetail.setItemName("运费")
                    orderDetail.setItemDesc("")
                    orderDetail.setItemSum(goodsFreight as Long)
                    orderDetail.setItemNum(1L)
                    orderDetSum = orderDetailService.addBasic(orderDetail);
                }
                if (orderDetSum > 0) {
                    //初始化支付接口
                    if (!"7551000001".equals(GlobalConstant.getString("mch_id"))) { //非测试商户ID
                        res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), tOrder.getTotalFee().toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    } else {
                        res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), 1.toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    }
                }
                ObjectMapper ompay = new ObjectMapper();
                ompay.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                PayResult custInfo = ompay.readValue(res, PayResult.class);
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.SUCCESS, custInfo.token_id)
            } else {
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "生成订单失败", null)
            }


        } catch (Exception e) {
            e.printStackTrace()
            logger.error("订单支付失败!")
            sessionCache.delCache(openid + "outtradeno");
            return new JsonResult<Object>(MessageConstant.FAILURE, null)
        } /*finally {

        }*/
    }

    /**
     * 商城订单快速支付
     */
    @RequestMapping(value = "kPay", method = RequestMethod.POST)
    @ResponseBody
    kPay(HttpServletRequest request, String orderId, String openid) {
        try {
            String res = "";
            //获取订单信息
          /*  Map<String,Object> params=[:];
            params <<[id:orderId];*/
            TOrder tOrder=orderService.findObjByKey(Long.valueOf(orderId)) as TOrder;
            if (tOrder!=null) {//插入详情
                    //初始化支付接口
                    if (!"7551000001".equals(GlobalConstant.getString("mch_id"))) { //非测试商户ID
                        res = PayMentApi.payInfo(openid, tOrder.getOutTradeNo(), tOrder.getGoodsName(), tOrder.getGoodsName(), tOrder.getTotalFee().toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    } else {
                        res = PayMentApi.payInfo(openid, tOrder.getOutTradeNo(), tOrder.getGoodsName(), tOrder.getGoodsName(), 1.toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    }
                ObjectMapper ompay = new ObjectMapper();
                ompay.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                PayResult custInfo = ompay.readValue(res, PayResult.class);
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.SUCCESS, custInfo.token_id)
            } else {
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "生成订单失败", null)
            }


        } catch (Exception e) {
            e.printStackTrace()
            logger.error("订单支付失败!")
            sessionCache.delCache(openid + "outtradeno");
            return new JsonResult<Object>(MessageConstant.FAILURE, null)
        } /*finally {

        }*/
    }

    /**
     * 电视维护费充值
     * 需要传递的参数产品名称 智能卡号 缴费金额 产品编号 订购长度
     *goodsName intelligentNo totalFee  reserve1  reserve2
     */
    @RequestMapping(value = "recharge", method = RequestMethod.POST)
    @ResponseBody
    recharge(HttpServletRequest request, TOrder tOrder, String openid) {
        try {
            //插入订单
            TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
            if (wechatSubscribe == null) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
            }
            //订购产品判断
            String outtradeno = ("" + Math.random() * 10).substring(2);//随机生成
            CalculatorDelegate calculatorDelegate= CalculatorHandler.getCalculatorPort();
            List<ResultVo> list=calculatorDelegate.wxChargePdtJudge(outtradeno,tOrder.intelligentNo,(tOrder.totalFee/100).toString(),tOrder.reserve1,tOrder.reserve2,"1","1000");
            ResultVo resultVo;
            if(list!=null && list.size()>0){
                resultVo=list.get(0) as ResultVo;
                switch (resultVo.result){
                 case "0":
                     break;
                    case "901": //缴费流水已经存在
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "订购产品检验异常")
                        break;
                    case "902":
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "产品不存在")
                        break;
                    case "903":
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "您当前未订购智能产品")
                        break;
                    case "904":
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "您已报停,不能充值")
                        break;
                    case "905"://操作员不存在
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "订购产品检验异常")
                        break;
                    default:
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "操作失败")
                }

            }else {
                return new JsonResult<Object>(MessageConstant.FAILURE, "调用广电接口失败")
            }
            String res = "";
            tOrder.setOutTradeNo(outtradeno)//商户订单号
            tOrder.setUserId(wechatSubscribe.getSubcribeId() as Long)//获取userId
            tOrder.setGoodsModule("3")//1:实体商品 2:套餐 3:收视费 4:虚拟商品  这里默认3
            tOrder.setAccountDate(DateUtil.getTimeToString());//账单日期
            tOrder.setCreateTime(new Date().getTime())
            tOrder.setPayFee(tOrder.getTotalFee())//目前支付金额等于总金额
            tOrder.payStatus = CommonConstant.PayStatus.NotPay.value//默认未支付
            tOrder.setIsActive(CommonConstant.IsActive.True.value)//默认有效
            Long orderSum = orderService.addBasic(tOrder);
            if (orderSum > 0) {//插入详情
                    //初始化支付接口
                    if (!"7551000001".equals(GlobalConstant.getString("mch_id"))) { //非测试商户ID
                        res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), tOrder.getTotalFee().toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    } else {
                        res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), 1.toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                    }
                ObjectMapper ompay = new ObjectMapper();
                ompay.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                PayResult custInfo = ompay.readValue(res, PayResult.class);
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.SUCCESS, custInfo.token_id)
            } else {
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "生成充值订单失败", null)
            }


        } catch (Exception e) {
            logger.error("充值订单支付失败!")
            sessionCache.delCache(openid + "outtradeno");
            return new JsonResult<Object>(MessageConstant.SYS_ERROR, null)
        }
    }


    /**
     * 电视维护费充值2
     * 需要传递的参数产品名称 智能卡号 缴费金额 产品编号 订购长度
     *goodsName intelligentNo totalFee  reserve1  reserve2
     */
    @RequestMapping(value = "recharge2", method = RequestMethod.POST)
    @ResponseBody
    recharge2(HttpServletRequest request, String id, String openid,String intelligentNo) {
        try {
            //插入订单
            TblWechatSubscribe wechatSubscribe = wechatSubService.findObj([openid: openid] as Map)
            if (wechatSubscribe == null) {
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "未获取到微信用户信息", null)
            }
            //获取电视维护费信息
            TGoodsInfo tGoodsInfo=goodsService.findObjByKey(Long.valueOf(id)) as TGoodsInfo;
            if(tGoodsInfo==null){
                return new JsonResult<Object>(MessageConstant.FAIL_QUERY.code, "未获取到电视维护费信息", null)
            }
            //订购产品判断
            String outtradeno = ("" + Math.random() * 10).substring(2);//随机生成
            CalculatorDelegate calculatorDelegate= CalculatorHandler.getCalculatorPort();
            List<ResultVo> list=calculatorDelegate.wxChargePdtJudge(outtradeno,intelligentNo,(tGoodsInfo.goodsPrice/100).toString(),tGoodsInfo.goodsNo,tGoodsInfo.goodsSum+"","1",GlobalConstant.getString("GdOperator"));
            ResultVo resultVo;
            if(list!=null && list.size()>0){
                resultVo=list.get(0) as ResultVo;
                switch (resultVo.result){
                    case "0":
                        break;
                    case "901": //缴费流水已经存在
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "订购产品检验异常")
                        break;
                    case "902":
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "产品不存在")
                        break;
                    case "903":
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "您当前未订购智能产品")
                        break;
                    case "904":
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "您已报停,不能充值")
                        break;
                    case "905"://操作员不存在
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "订购产品检验异常")
                        break;
                    default:
                        return new JsonResult<Object>(MessageConstant.FAILURE_JUDGE, "操作失败")
                }

            }else {
                return new JsonResult<Object>(MessageConstant.FAILURE, "调用广电接口失败")
            }
            String res = "";
            TOrder tOrder=new TOrder();
            tOrder.setGoodsName(tGoodsInfo.getDetails()+tGoodsInfo.getGoodsName())
            tOrder.setGoodsNum(tGoodsInfo.getGoodsSum())
            tOrder.setIntelligentNo(intelligentNo);
            tOrder.setReserve1(tGoodsInfo.getGoodsNo())
            tOrder.setOutTradeNo(outtradeno)//商户订单号
            tOrder.setUserId(wechatSubscribe.getSubcribeId() as Long)//获取userId
            tOrder.setGoodsModule("3")//1:实体商品 2:套餐 3:收视费 4:虚拟商品  这里默认3
            tOrder.setAccountDate(DateUtil.getTimeToString());//账单日期
            tOrder.setCreateTime(new Date().getTime())
            tOrder.setPayFee(tGoodsInfo.getGoodsPrice() as Long)//目前支付金额等于总金额
            tOrder.setTotalFee(tGoodsInfo.getGoodsPrice() as Long)
            tOrder.payStatus = CommonConstant.PayStatus.NotPay.value//默认未支付
            tOrder.setReserve2(openid);
            tOrder.setIsActive(CommonConstant.IsActive.True.value)//默认有效
            Long orderSum = orderService.addBasic(tOrder);
            if (orderSum > 0) {
                //初始化支付接口
                if (!"7551000001".equals(GlobalConstant.getString("mch_id"))) { //非测试商户ID
                    res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), tOrder.getTotalFee().toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                } else {
                    res = PayMentApi.payInfo(openid, outtradeno, tOrder.getGoodsName(), tOrder.getGoodsName(), 1.toString(), DateUtil.getDateTime(), "",tOrder.id+"",openid)
                }
                ObjectMapper ompay = new ObjectMapper();
                ompay.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                PayResult custInfo = ompay.readValue(res, PayResult.class);
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.SUCCESS, custInfo.token_id)
            } else {
                sessionCache.delCache(openid + "outtradeno");
                return new JsonResult<Object>(MessageConstant.FAILURE.code, "生成充值订单失败", null)
            }


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("充值订单支付失败!")
            sessionCache.delCache(openid + "outtradeno");
            return new JsonResult<Object>(MessageConstant.SYS_ERROR, null)
        }
    }



    /**
     * 获取商户订单号
     * @param request
     * @return
     */
    @RequestMapping(value = "getOuttradeno", method = RequestMethod.GET)
    @ResponseBody
    getOuttradeno(HttpServletRequest request, String openid) {
        String outtradeno = ("" + Math.random() * 10).substring(2);//随机生成
        sessionCache.setCache(openid + "outtradeno", outtradeno)
        return new JsonResult<Object>(MessageConstant.SUCCESS, outtradeno)
    }

}
